package com.boot.project.module.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.project.core.constant.RedisConstant;
import com.boot.project.core.enums.code.impl.commonCode.ResultCode;
import com.boot.project.core.enums.code.impl.systemCode.RoleCode;
import com.boot.project.core.exception.CustomerException;
import com.boot.project.core.model.system.criteria.RoleCriteria;
import com.boot.project.core.model.system.dto.RoleAssignDto;
import com.boot.project.core.model.system.dto.RoleSaveDto;
import com.boot.project.core.model.system.entity.Role;
import com.boot.project.core.model.system.entity.RoleResource;
import com.boot.project.core.model.system.entity.User;
import com.boot.project.module.system.mapper.RoleMapper;
import com.boot.project.module.system.mapper.RoleResourceMapper;
import com.boot.project.module.system.mapper.UserMapper;
import com.boot.project.module.system.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: tsing
 * @create: 2021-01-21 22:21
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页条件查询
     *
     * @param criteria 查询条件
     * @return
     */
    @Override
    public Page<Role> page(RoleCriteria criteria) {
        // 1.封装查询对象
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(criteria.getRoleName())) {
            wrapper.like("role_name", criteria.getRoleName());
        }
        wrapper.orderByAsc("sort");
        // 2.进行查询
        Page<Role> pageInfo = new Page<>(criteria.getPage(), criteria.getSize());
        roleMapper.selectPage(pageInfo, wrapper);
        // 3.结果处理
        if (pageInfo.getTotal() == 0) {
            throw new CustomerException(ResultCode.RETURN_DATA_NOT_FOUND);
        }
        return pageInfo;
    }

    /**
     * 新增角色信息
     *
     * @param roleSaveDto 角色信息
     */
    @Override
    public void add(RoleSaveDto roleSaveDto) {
        // 1.校验参数
        Role dbRole = roleMapper.findByRoleName(roleSaveDto.getRoleName());
        if (dbRole != null) {
            throw new CustomerException(RoleCode.EXISTS_ROLE_NAME);
        }
        // 2.封装数据
        Role role = new Role(roleSaveDto);
        // 3.进行保存
        int i = roleMapper.insert(role);
        // 4.对结果进行处理
        if (i != 1) {
            throw new CustomerException(ResultCode.INSERT_FAILURE);
        }
    }

    /**
     * 根据id查询角色信息
     *
     * @param id 角色id
     * @return
     */
    @Override
    public Role findOne(Long id) {
        // 1.进行查询
        Role dbRole = roleMapper.selectById(id);
        // 2.对结果进行判断
        if (dbRole == null) {
            throw new CustomerException(ResultCode.RETURN_DATA_NOT_FOUND);
        }
        return dbRole;
    }

    /**
     * 更新角色信息
     *
     * @param roleSaveDto 角色信息
     */
    @Override
    public void edit(RoleSaveDto roleSaveDto) {
        // 1.校验参数
        if (roleSaveDto.getId() == null) {
            throw new CustomerException(ResultCode.HANDLE_DATA_NOT_EXISTED, "更新时，角色id不能为空");
        }
        Role dbRole = roleMapper.selectById(roleSaveDto.getId());
        if (dbRole == null) {
            throw new CustomerException(ResultCode.RETURN_DATA_NOT_FOUND, "更新时，没有找到需要更新的角色");
        }
        Role tempRole = roleMapper.findByRoleName(roleSaveDto.getRoleName());
        if (tempRole != null && !tempRole.getId().equals(roleSaveDto.getId())) {
            throw new CustomerException(RoleCode.EXISTS_ROLE_NAME);
        }
        // 2.封装数据
        BeanUtils.copyProperties(roleSaveDto, dbRole);
        // 3.进行保存
        int i = roleMapper.updateById(dbRole);
        // 4.对结果进行处理
        if (i != 1) {
            throw new CustomerException(ResultCode.UPDATE_FAILURE);
        }
    }

    /**
     * 批量删除角色信息
     *
     * @param ids 角色id的集合
     */
    @Override
    public void delete(List<Long> ids) {
        // 1.参数校验
        if (CollectionUtil.isEmpty(ids)) {
            throw new CustomerException(ResultCode.HANDLE_DATA_NOT_EXISTED, "没有需要删除的角色信息");
        }
        // 2.只有角色下没有用户信息才能删除
        for (Long roleId : ids) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id", roleId);
            Integer count = userMapper.selectCount(wrapper);
            if (count != 0) {
                throw new CustomerException(RoleCode.EXISTS_USERS_BELONG_THIS_ROLE, "id为"
                        + roleId + "的角色下仍有用户存在，删除失败");
            }
        }
        // 3.进行删除
        int i = roleMapper.deleteBatchIds(ids);
        // 4.对结果进行处理
        if (i != ids.size()) {
            throw new CustomerException(ResultCode.DELETE_FAILURE);
        }
    }

    /**
     * 查询所有角色
     *
     * @return
     */
    @Override
    public List<Role> findAll() {
        List<Role> roles = roleMapper.selectList(null);
        if (CollectionUtil.isEmpty(roles)) {
            throw new CustomerException(ResultCode.RETURN_DATA_NOT_FOUND);
        }
        return roles;
    }

    /**
     * 给角色分配权限
     *
     * @param roleAssignDto 角色分配权限的实体
     */
    @Override
    @Transactional
    public void assignPermission(RoleAssignDto roleAssignDto) {
        // 1.校验数据
        Long roleId = roleAssignDto.getRoleId();
        Role dbRole = roleMapper.selectById(roleId);
        if (ObjectUtil.isNull(dbRole)) {
            throw new CustomerException(ResultCode.RETURN_DATA_NOT_FOUND, "分配权限时，没有找到角色的信息");
        }
        // 2.删除原来的
        List<RoleResource> roleResources = roleResourceMapper.findByRoleId(roleId);
        if (CollectionUtil.isNotEmpty(roleResources)) {
            List<Long> needDeleteIds = roleResources.stream().map(RoleResource::getId).collect(Collectors.toList());
            int i = roleResourceMapper.batchDeleteRoleResource(needDeleteIds);
            if (i != needDeleteIds.size()) {
                throw new CustomerException(RoleCode.ASSIGN_RESOURCE_FAILURE);
            }
        }
        // 3.新增现在的
        if (CollectionUtil.isNotEmpty(roleAssignDto.getResourceIds())) {
            List<RoleResource> needInsertList = new ArrayList<>();
            buildRoleResource(needInsertList, roleAssignDto);
            int i = roleResourceMapper.batchInsertRoleResource(needInsertList);
            if (i != roleAssignDto.getResourceIds().size()) {
                throw new CustomerException(RoleCode.ASSIGN_RESOURCE_FAILURE);
            }
        }
        // 4.删除缓存
        redisTemplate.delete(RedisConstant.REDIS_ROLE_PROFILE_PREFIX + roleId);
    }

    /**
     * 构建中间表的数据
     * @param list 中间表
     * @param roleAssignDto 角色分配权限的实体
     */
    private void buildRoleResource(List<RoleResource> list, RoleAssignDto roleAssignDto) {
        // 5,5是mp默认的雪花算法的参数
        Snowflake snowflake = IdUtil.getSnowflake(5L, 5L);
        for (Long resourceId : roleAssignDto.getResourceIds()) {
            RoleResource roleResource = new RoleResource(snowflake.nextId(), roleAssignDto.getRoleId(), resourceId);
            list.add(roleResource);
        }
    }
}
